package com.dnw.shyfunny;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.NavigationView;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;

import com.chaychan.library.BottomBarItem;
import com.chaychan.library.BottomBarLayout;
import com.dnw.adapter.MainTabAdapter;
import com.dnw.base.BaseActivityDr;
import com.dnw.base.BaseFragment;
import com.dnw.base.MyApp;
import com.dnw.event.TabRefreshEvent;
import com.dnw.fragment.GifFragment;
import com.dnw.fragment.ImageFragment;
import com.dnw.fragment.LiveFragment;
import com.dnw.fragment.RecommendFragment;
import com.dnw.fragment.ShyFragment;
import com.dnw.fragment.TextFragment;
import com.dnw.httpUtil.ApiRetrofit;
import com.dnw.httpUtil.ApiService;
import com.dnw.modle.Result;
import com.dnw.modle.TabEntity;
import com.dnw.modle.VersionData;
import com.dnw.util.AppUtil;

import com.dnw.util.ConstanceValue;
import com.dnw.util.DownloadProgressReceiver;
import com.dnw.util.ShareUtil;
import com.dnw.util.SharedPreferencesMgr;
import com.dnw.util.UIUtils;
import com.dnw.view.NoScrollViewPager;
import com.dnw.view.tabLayoutLib.CommonTabLayout;
import com.dnw.view.tabLayoutLib.CustomTabEntity;
import com.google.gson.Gson;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.filedownloader.notification.BaseNotificationItem;
import com.liulishuo.filedownloader.notification.FileDownloadNotificationHelper;
import com.liulishuo.filedownloader.notification.FileDownloadNotificationListener;
import com.liulishuo.filedownloader.util.FileDownloadHelper;


import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import cn.pedant.SweetAlert.SweetAlertDialog;
import flyn.Eyes;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import rx.Subscriber;

import static com.dnw.base.ApiConstant.SharedPreferencesEnum.PASSED;
import static com.dnw.base.ApiConstant.approvedEnum.APPROVED;
import static com.dnw.base.ApiConstant.approvedEnum.NOT_APPROVED;

/**
 * @author diangoJ
 */
public class MainActivity extends BaseActivityDr implements NavigationView.OnNavigationItemSelectedListener, DownloadProgressReceiver.Message{
    private CommonTabLayout mTablayout;
    private NoScrollViewPager mViewPager;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private List<BaseFragment> fragments;
    private ProgramDetailActivity programDetailActivity=new ProgramDetailActivity();
    String appFile = Environment.getExternalStorageDirectory().getPath() + File.separator + "xiudou_app" + File.separator + "program" + ".apk";
    //    @Bind(R.id.bottom_bar)
    BottomBarLayout mBottomBarLayout;
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @Override
    protected void bindViews() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApp.getInstance().setmMainActivity(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        setEnableSwipe(false);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        doViewGone(navigationView);
        findId();
        initTab();
    }

    // FIXME: 2018/1/4 渠道黑名单
    private void doViewGone(NavigationView navigationView) {
        if (!SharedPreferencesMgr.getBoolean(PASSED.name() + AppUtil.getVersionCode(this), APPROVED.isStatus())) {
            Menu menu = navigationView.getMenu();
            menu.getItem(2).setVisible(false);
        }
    }

    private MainTabAdapter mTabAdapter;

    @Override
    protected void setListener() {
        mTabAdapter = new MainTabAdapter(fragments, getSupportFragmentManager());
        mViewPager.setAdapter(mTabAdapter);
        mViewPager.setOffscreenPageLimit(fragments.size()+1);
        mBottomBarLayout.setViewPager(mViewPager);
        mBottomBarLayout.setOnItemSelectedListener(new BottomBarLayout.OnItemSelectedListener() {
            @Override
            public void onItemSelected(BottomBarItem bottomBarItem, int position) {
                setStatusBarColor(position);//设置状态栏颜色

                JCVideoPlayer.releaseAllVideos();//底部页签切换或者是下拉刷新，释放资源

                //如果点击了其他条目
                BottomBarItem bottomItem = mBottomBarLayout.getBottomItem(0);
                bottomItem.setIconSelectedResourceId(R.mipmap.bg);//更换为原来的图标

                cancelTabLoading(bottomItem);//停止旋转动画
            }
        });
        //        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        //            @Override
        //            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        //
        //            }
        //
        //            @Override
        //            public void onPageSelected(int position) {
        //                mTablayout.setCurrentTab(position);
        //            }
        //
        //            @Override
        //            public void onPageScrollStateChanged(int state) {
        //
        //            }
        //        });
    }

    private int[] mStatusColors = new int[]{
            R.color.bg_funny,
            R.color.bg_funny,
            R.color.bg_funny,
            R.color.bg_funny,
            R.color.bg_funny,
            R.color.bg_funny,
    };

    private void setStatusBarColor(int position) {
        if (position == 6) {
            //如果是我的页面，状态栏设置为透明状态栏
            Eyes.translucentStatusBar(MainActivity.this, true);
        } else {
            Eyes.setStatusBarColor(MainActivity.this, UIUtils.getColor(mStatusColors[position]));
        }
    }

    /**
     * 停止首页页签的旋转动画
     */
    private void cancelTabLoading(BottomBarItem bottomItem) {
        Animation animation = bottomItem.getImageView().getAnimation();
        if (animation != null) {
            animation.cancel();
        }
    }

    private void postTabRefreshEvent(BottomBarItem bottomBarItem, int position, String channelCode) {
        TabRefreshEvent event = new TabRefreshEvent();
        event.setChannelCode(channelCode);
        event.setBottomBarItem(bottomBarItem);
        event.setHomeTab(position == 0);
        EventBus.getDefault().post(event);//发送下拉刷新事件
    }

    /**
     * 初始化tab
     */
    private void initTab() {
        fragments = getFragments();
        //        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments, getNames());
        //
        //        mTablayout.setTabData(mTabEntities);
        //        mViewPager.setAdapter(myFragmentPagerAdapter);
    }

    /**
     * 假数据
     *
     * @return
     */
    public String[] getNames() {
        String[] mNames = new String[]{"推荐", "gif", "图片", "段子"};
        for (String str : mNames) {
            mTabEntities.add(new TabEntity(str));
        }

        return mNames;
    }

    public List<BaseFragment> getFragments() {
        List<BaseFragment> fragments = new ArrayList<>();
        fragments.add(new RecommendFragment());
        fragments.add(new GifFragment());
        fragments.add(new ImageFragment());
        fragments.add(new TextFragment());
        fragments.add(new LiveFragment());
        if (SharedPreferencesMgr.getBoolean(PASSED.name() + AppUtil.getVersionCode(this), NOT_APPROVED.isStatus())) {
            fragments.add(new ShyFragment());
        } else {
            mBottomBarLayout.removeViewAt(4);
        }
        return fragments;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
//           Intent intent = new Intent(this, SearchActivity.class);
//            startActivity(intent);
            startActivity(new Intent(this, SearchActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * @param item 导航栏选项
     * @return
     */
    @SuppressWarnings("StatementWithEmptyBody")
    @Override

    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Intent intent;
        if (id == R.id.random) {
            if (mViewPager.getCurrentItem() == 0) {
                RecommendFragment exFragment = (RecommendFragment) mTabAdapter.getCurrentFragment();
                exFragment.jumpToPosition();
            } else if (mViewPager.getCurrentItem() == 1) {
                GifFragment exFragment = (GifFragment) mTabAdapter.getCurrentFragment();
                exFragment.jumpToPosition();
            } else if (mViewPager.getCurrentItem() == 2) {
                ImageFragment exFragment = (ImageFragment) mTabAdapter.getCurrentFragment();
                exFragment.jumpToPosition();
            } else if (mViewPager.getCurrentItem() == 3) {
                TextFragment exFragment = (TextFragment) mTabAdapter.getCurrentFragment();
                exFragment.jumpToPosition();
            }
        } else if (id == R.id.local) {
            intent = new Intent(this, LocalActivity.class);
            startActivity(intent);
        } else if (id == R.id.program) {
            intent = new Intent(this, ProgramActivity.class);
            startActivity(intent);
        } else if (id == R.id.opinion) {
            intent = new Intent(this, OpinionActivity.class);
            startActivity(intent);
        } else if (id == R.id.recommend) {
            ShareUtil.showShare(this);
//            new ShareQQ(MainActivity.this).onShareApk();

//            new ShareUM(this);
        } else if (id == R.id.about) {
            intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        onCreate(null);
        getReNewAl();
    }

    public void refresh() {
        mViewPager.setCurrentItem(0);
//        mTabAdapter.notifyDataSetChanged();
        RecommendFragment exFragment = (RecommendFragment) mTabAdapter.getCurrentFragment();
        exFragment.loadData();
    }

    /**
     * 初始化id
     */
    private void findId() {

        //        mTablayout = (CommonTabLayout) findViewById(R.id.uc_tablayout);
        mViewPager = (NoScrollViewPager) findViewById(R.id.uc_viewpager);
        mBottomBarLayout = (BottomBarLayout) findViewById(R.id.bottom_bar);
    }

    SweetAlertDialog sweetAlertDialog;

    private void getReNewAl() {
        Map<String, String> mMap = new HashMap<>();
        try {
            addSubscription(mApiService.getAppVersion(), new Subscriber<Result>() {

                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(Result result) {
                    if (result != null) {
                        VersionData versionData = new Gson().fromJson(result.data.toString(), VersionData.class);
                        if (AppUtil.compareVersion(versionData.targetVersion, AppUtil.getVersionName(MainActivity.this)) < 0) {
                            if (AppUtil.compareVersion(versionData.minVersion, AppUtil.getVersionName(MainActivity.this)) < 0) {
                                if (sweetAlertDialog == null) {
                                    sweetAlertDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE);
                                }
                                try {
                                    sweetAlertDialog.setTitleText("发现新版本");
                                    sweetAlertDialog.setContentText("");
                                    sweetAlertDialog.setConfirmText("立马更新");
                                    sweetAlertDialog.setCancelText("以后再说");
                                    sweetAlertDialog.showCancelButton(true);
                                    sweetAlertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        /**
                                         * @param sDialog
                                         */
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog
                                                    .changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
                                            sweetAlertDialog.setTitleText("下载更新");
                                            sweetAlertDialog.showCancelButton(false);

                                            FileDownloader.getImpl().create("http://106.15.202.6:81/download/apk/shyfunny.apk")
                                                    .setPath(appFile)
                                                    .setListener(new NotificationListener(new FileDownloadNotificationHelper<NotificationItem>()))
                                                    .start();
                                            if (appFile!=null){

                                            }
                                        }
                                    });
                                    sweetAlertDialog.show();
                                    sweetAlertDialog.setCancelable(false);
                                } catch (Exception e) {
                                    Log.e("---", "---", e);
                                }
                            } else {
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            Log.e("---------", "e", e);
        }


//        new HttpUtils(getActivity() ,UrlConfig.HTTPTITLE).post(UrlConfig.RENEWAL, mMap, new HttpUtils.HttpCallback() {
//
//            @Override
//            public void onSuccess(String data) {
//                JSONObject obj = JSON.parseObject(data);
//                if (obj.getBoolean("success")) {
//                    isUpdate = false;
//                    JSONObject map = obj.getJSONObject("map");
//                    maxVersion = map.getString("maxVersion");
//                    JSONObject sysAppRenewal = map.getJSONObject("sysAppRenewal");
//                    if(sysAppRenewal!=null){
//                        isForceUpdate = sysAppRenewal.getString("isForceUpdate");
//                        version_renewal = sysAppRenewal.getString("version");
//                        content = sysAppRenewal.getString("content");
//                    }
//                    if(maxVersion!=null&&!maxVersion.equalsIgnoreCase("")){
//                        if (stringCut.compareVersion(maxVersion,LocalApplication.localVersion)>0) {
//                            if(sysAppRenewal!=null&&!isForceUpdate.equalsIgnoreCase("")&&isForceUpdate!=null&&!version_renewal.equalsIgnoreCase("")&&version_renewal!=null){
//                                if (stringCut.compareVersion(version_renewal,LocalApplication.localVersion)==1) {
//                                    dialog = showAlertDialog("版本更新", stringCut.HuanHang_Cut(content), new String[]{"立即更新"}, false, false, "updatesingle");
////													isUpdate = true;
//                                } else {
//                                    dialog = showAlertDialog("版本更新", stringCut.HuanHang_Cut(content), new String[]{"取消","立即更新"}, true, false, "update");
//                                }
//                            }else{
//                                dialog = showAlertDialog("版本更新", stringCut.HuanHang_Cut(content), new String[]{"取消","立即更新"}, true, false, "update");
//                            }
//                        }else{
//                            if (!preferences.getBoolean("login", false)) {
//                                showPopupWindowRegist();
//                            }
//                        }
//                    }

//                }
//            }
//        });
    }

    @Override
    public void update(String name, int progress) {
        UIUtils.showToast("正在下载(" + progress + "%)");

    }
    public class NotificationListener extends FileDownloadNotificationListener {


        private static final String TAG = "NotificationListener";


        public NotificationListener(FileDownloadNotificationHelper helper) {
            super(helper);
        }

        @Override
        protected BaseNotificationItem create(BaseDownloadTask task) {
            return new NotificationItem(task.getId(),
                    "", "");
        }

        @Override
        public void destroyNotification(BaseDownloadTask task) {
            super.destroyNotification(task);

            if (task.getStatus() == FileDownloadStatus.completed) {
                File file= new File(appFile);
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                Uri apkUri =
                        FileProvider.getUriForFile(MainActivity.this, "com.dnw.shyfunny.fileprovider", file);

                Intent intent = new Intent(Intent.ACTION_VIEW);
                // 由于没有在Activity环境下启动Activity,设置下面的标签
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                startActivity(intent);
            }
        }

    }
    public class NotificationItem extends BaseNotificationItem {

        PendingIntent pendingIntent;
        NotificationCompat.Builder builder;

        private NotificationItem(int id, String title, String desc) {
            super(id, title, desc);
            builder = new NotificationCompat.
                    Builder(FileDownloadHelper.getAppContext());

            builder.setDefaults(Notification.DEFAULT_LIGHTS)
                    .setOngoing(true)
                    .setPriority(NotificationCompat.PRIORITY_MIN)
                    .setContentTitle(getTitle())
                    .setContentText(desc)
                    .setSmallIcon(R.mipmap.ic_launcher);
        }

        @Override
        public void show(boolean statusChanged, int status, boolean isShowProgress) {
            long total = 100;
            int progress = 0;
            if (getTotal() != 0) {
                progress = (int) ((float) getSofar() / (float) getTotal() * 100);
            }
            builder.setContentTitle(getTitle() + "(" + progress + "%)")
                    .setContentText(getDesc());
            if (statusChanged) {
                builder.setTicker(getDesc());
            }
            builder.setProgress(getTotal(), getSofar(), !isShowProgress);
            getManager().notify(getId(), builder.build());
            Intent intent = new Intent();
            intent.setAction(ConstanceValue.RECOMMEND_APP_DOWNLOAD_PROGRESS);
            intent.putExtra("name", getTitle());
            intent.putExtra("progress", progress);
            FileDownloadHelper.getAppContext().sendBroadcast(intent);
        }

    }
}



